package com.bibrApp.difu.base;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.bibrApp.difu.utils.ToastUtils;
import com.trello.rxlifecycle2.components.support.RxFragment;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import butterknife.ButterKnife;

public abstract class BaseFragment<T extends BasePresenter> extends RxFragment {
    protected T presenter;

    protected abstract int getLayoutResId();

    protected abstract void initPresenter();


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        View view = inflater.inflate(getLayoutResId(), container, false);
        ButterKnife.bind(this, view);
        initPresenter();
        return view;
    }

    @Override
    public void onPause() {
        super.onPause();

    }


    /**
     * Fragment替换(核心为隐藏当前的,显示现在的,用过的将不会destrory与create)
     */
    private Fragment currentFragment;

    protected void smartReplaceFragment(@IdRes int flId, Fragment toFragment, String tag) {
        FragmentManager manager = getChildFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        // 如有当前在使用的->隐藏当前的
        if (currentFragment != null) {
            transaction.hide(currentFragment);
        }
        // toFragment之前添加使用过->显示出来
        if (manager.findFragmentByTag(tag) != null) {
            transaction.show(toFragment);
        } else {// toFragment还没添加使用过->添加上去
            transaction.add(flId, toFragment, tag);
        }
//        transaction.setMaxLifecycle(toFragment, Lifecycle.State.RESUMED);
        transaction.commitAllowingStateLoss();
        // toFragment更新为当前的
        currentFragment = toFragment;
    }

    protected void smartReplaceFragment(@IdRes int flId, Fragment toFragment) {
        smartReplaceFragment(flId, toFragment, toFragment.getClass().getSimpleName());
    }

    public void showToast(String msg) {
        if (TextUtils.isEmpty(msg)) {
            return;

        }
        ToastUtils.ShowToast(getContext(), msg);
    }

    public void startActivity(Class<?> cls) {
        startActivity(new Intent(getContext(), cls));
    }
}
